package com.lp.juc;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.locks.ReentrantLock;

public class CASTest {
    public static void main(String[] args) throws Exception{
        ReentrantLock lock = new ReentrantLock();
        Integer a = 0;
        System.out.println("a的值："+a);
        Class<Unsafe> unsafeClass = Unsafe.class;
        Field theUnsafeField = unsafeClass.getDeclaredField("theUnsafe");
        Unsafe unsafe1 = unsafeClass.newInstance();
        Method arrayBaseOffset = unsafeClass.getDeclaredMethod("arrayBaseOffset",Class.class);
        Integer offset = (Integer)arrayBaseOffset.invoke(unsafe1, a.getClass());
        boolean orignialAccessible = theUnsafeField.isAccessible();
        theUnsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe)theUnsafeField.get(null); //unsafeInstance就是Unsafe的实例
        //int i = unsafe.arrayBaseOffset(a.getClass());
        boolean b = unsafe.compareAndSwapInt(a, offset, 0, 1);
        System.out.println(b);
        System.out.println("a的值："+a);
    }
}
